package com.zx.flow.db.convert;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.flow.api.config.FlowConfig;
import com.zx.flow.api.execute.model.FlowContext;
import com.zx.flow.api.execute.model.FlowNode;
import com.zx.flow.api.util.Util;
import com.zx.flow.db.entity.FlowConfigEntity;
import com.zx.flow.db.entity.FlowContextEntity;
import com.zx.flow.db.entity.FlowNodeEntity;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;

/**
 * mapstruct与idea、jdk不适配
 */
public class DbConvert {

    public static FlowConfigEntity to(FlowConfig a) {
        if (StringUtils.isEmpty(a.getId())) {
            a.setId(Util.uniqueId(a));
        }
        FlowConfigEntity b = new FlowConfigEntity();
        BeanUtils.copyProperties(a, b);
        // 特殊处理
        b.setConfig(Util.getJsonStr(a));
        return b;
    }

    public static FlowConfig to(FlowConfigEntity a) {
        FlowConfig config = Util.getJavaObject(a.getConfig(), FlowConfig.class);
        config.setVersion(a.getVersion());
        config.setEnable(a.getEnable());
        config.setCreateTime(a.getCreateTime());
        config.setUpdateTime(a.getUpdateTime());
        config.setSecretId(a.getSecretId());
        return config;
    }

    public static FlowContextEntity to(FlowContext a) {
        FlowContextEntity b = new FlowContextEntity();
        BeanUtils.copyProperties(a, b);
        return b;
    }

    public static FlowContext to(FlowContextEntity a) {
        FlowContext b = new FlowContext();
        BeanUtils.copyProperties(a, b);
        return b;
    }

    public static FlowNodeEntity to(FlowNode a) {
        FlowNodeEntity b = new FlowNodeEntity();
        BeanUtils.copyProperties(a, b);
        return b;
    }

    public static FlowNode to(FlowNodeEntity a) {
        FlowNode b = new FlowNode();
        BeanUtils.copyProperties(a, b);
        return b;
    }


    /**
     * @Description:转换为 IPage 对象
     * @Date: 2019/10/31 9:40
     */
    public static <S, T> IPage<T> to(IPage<S> page, Function<S, T> mapper) {
        IPage<T> pageResult = new Page(page.getCurrent(), page.getSize(), page.getTotal());
        pageResult.setPages(page.getPages());
        // 类型转换
        List<T> targetList = page.getRecords().stream().map(mapper).collect(Collectors.toList());
        pageResult.setRecords(targetList);
        return pageResult;
    }


}
